package com.mrzhou.msg.service.impl;

import com.mrzhou.common.constant.CommonConstant;
import com.mrzhou.common.entity.msg.MailInfo;
import com.mrzhou.common.util.ValidUtil;
import com.mrzhou.core.tool.api.R;
import com.mrzhou.core.tool.utils.DigestUtil;
import com.mrzhou.data.support.RedisService;
import com.mrzhou.msg.service.IMailService;
import com.mrzhou.msg.vo.req.ValidMailPhoneReq;
import com.mrzhou.web.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.internet.MimeMessage;

@Service
@Slf4j
public class MailService implements IMailService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private RedisService redisService;

    @Value("${spring.mail.from}")
    private String from = System.getProperty("spring.mail.from");

    public R<String> sendSimpleMail(String title, String msg, String... mail) {
        try{
            //创建SimplmailMessage对象
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from); // 发送人
            message.setTo(mail); // 接收人
            message.setSubject(title); // 主题
            message.setText(msg); // 消息体
            javaMailSender.send(message); // 发送邮件
            return R.success("邮件发送成功");
        } catch (Exception e) {
            log.error(e.getLocalizedMessage());
            return R.fail("邮件发送失败！"+e);
        }

    }

    public R<String> sendHtmlMail(String title, String msg, String... mail) {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(from);
            //邮件接收人
            messageHelper.setTo(mail);
            //邮件主题
            message.setSubject(title);
            //邮件内容，html格式
            messageHelper.setText(msg, true);
            //发送
            javaMailSender.send(message);
            return R.success("邮件发送成功！");
        } catch (Exception e) {
            log.error("发送邮件时发生异常！", e.getLocalizedMessage());
            return R.fail("邮件发送失败！"+e);
        }
    }

    public R<String> sendAttachmentMail(String title, String msg, MultipartFile file, String... mail) {
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(mail);
            helper.setSubject(title);
            helper.setText(msg, true);
            helper.addAttachment(file.getName(), file.getResource());
            javaMailSender.send(message);
            //日志信息
            return R.success("邮件发送成功！");
        } catch (Exception e) {
            log.error("发送邮件时发生异常！", e);
            return R.fail("邮件发送失败！" + e);
        }
    }

    public R<String> validMailCode(ValidMailPhoneReq req) {
        // 参数校验
        if (!ValidUtil.isEmail(req.getMailPhone())) {
            return R.fail("请输入正确的邮箱地址");
        }
        if(!ValidUtil.validMailCodeType(req.getType())) {
            return R.fail("非法的验证码类型: " + req.getType());
        }
        String clientIp = req.getClientIP();
        if(!StringUtils.isNotBlank(req.getClientIP())) {
            clientIp = WebUtil.getIp();
        }

        // 获取key的信息
        String key = CommonConstant.MAIL_CODE_KEY_PREFIX + DigestUtil.md5Hex(req.getMailPhone()  + ":" + req.getClientIP() + ":" + req.getType());
        MailInfo info = redisService.get(key, MailInfo.class);

        if(null == info) {
            return R.fail("邮箱验证码已过期, 请重新获取");
        }

        if(info.getStatus() != CommonConstant.MAIL_CODE_STATUS_INIT) {
            return R.fail("邮箱验证码已使用, 请重新获取");
        }

        if(!req.getCode().equals(info.getMailCode())) {
            return R.fail("邮箱验证码不正确, 请重新输入");
        }

        redisService.remove(key);
        return R.success("邮箱验证码检验成功");
    }

}
